﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using Microsoft.SharePoint.Client;

namespace SharePointTagCloud.Silverlight
{
    public class SharePointCOMTagData : SharePointTagCloud.Silverlight.ITagData
    {
        private ListItemCollection listItems;
        private List list;
        public Dictionary<string, int> tags { get; set; }
        public List<TagLink> tagLinks { get; set; }
        public string LinkDetails { get; set; }
        private ClientContext context;
        private string defaultUrl;

        public event DataLoadEvent DataLoaded;


        public SharePointCOMTagData()
        {
            tags = new Dictionary<string, int>();
            tagLinks = new List<TagLink>();
            context = new ClientContext(ApplicationContext.Current.Url);
        }

        public void GetData()
        {
            if (string.IsNullOrEmpty(LinkDetails))
            { throw new Exception("You must specify LinkDetails as the List name"); }
            list = context.Web.Lists.GetByTitle(LinkDetails);
            context.Load(list);
            context.ExecuteQueryAsync(new ClientRequestSucceededEventHandler(OnRequestSucceeded), new ClientRequestFailedEventHandler(OnRequestFailed));
        }

        private void OnRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
        { // this is not called on the UI thread
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml =
                @"<View>
                <Query>
                </Query>
                <RowLimit>1000</RowLimit>
              </View>";
            list.RefreshLoad();
            listItems = list.GetItems(camlQuery);
            context.Load(
                 listItems,
                 items => items.Include(
                     item => item["Title"],
                     item => item["Id"]));

            context.ExecuteQueryAsync(new ClientRequestSucceededEventHandler(OnListItemRequestSucceeded), new ClientRequestFailedEventHandler(OnRequestFailed));
        }

        private void OnListItemRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
        {
            PopulateData();
        }

        private void OnRequestFailed(Object sender, ClientRequestFailedEventArgs args)
        {
        }

        private void PopulateData()
        {
            defaultUrl = list.DefaultDisplayFormUrl;
            foreach (ListItem listItem in listItems)
            {
                Uri itemUri = new Uri(ApplicationContext.Current.Url + list.DefaultDisplayFormUrl + "?id=" + listItem.Id.ToString());
                foreach (KeyValuePair<string, object> text in listItem.FieldValues)
                {
                    string wordText = StripHtmlTags(text.Value.ToString());
                    string[] words = wordText.Split(' ');
                    foreach (string word in words)
                    {
                        tagLinks.Add(new TagLink(word, itemUri, text.Value.ToString()));
                        if (!tags.ContainsKey(word))
                        { tags.Add(word, 1); }
                        else
                        { tags[word] = tags[word] + 1; }
                    }
                }
            }
            DataLoaded();
        }

        private string StripHtmlTags(string value)
        {
            int length = 0;
            int.TryParse(value, out length);

            // Remove HTML tags and empty newlines and spaces and leading spaces
            string formattedValue = Regex.Replace(value as string, "<.*?>", "");
            formattedValue = Regex.Replace(formattedValue, @"\n+\s+", "\n\n");
            formattedValue = formattedValue.TrimStart(' ');
            formattedValue = HttpUtility.HtmlDecode(formattedValue);
            if (length > 0 && formattedValue.Length >= length)
                formattedValue = formattedValue.Substring(0, length - 1);
            return formattedValue;
        }
    }
}
